using log4net;
using Mathmall.Administration.Exceptions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Mathmall.Administration.Filter;

public class GlobalExceptionFilter : IAsyncExceptionFilter
{
    private static readonly ILog _logger = LogManager.GetLogger(typeof(GlobalExceptionFilter));
    private readonly IWebHostEnvironment _webHostEnvironment;

    public GlobalExceptionFilter(IWebHostEnvironment webHostEnvironment)
    {
        _webHostEnvironment = webHostEnvironment;
    }

    public Task OnExceptionAsync(ExceptionContext context)
    {
        if (context.Exception is CustomException customException && _webHostEnvironment.IsDevelopment())
        {
            _logger.Error(customException);
            context.Result = new JsonResult(customException) { ContentType = "application/json" };
            context.ExceptionHandled = true;
        }

        return Task.CompletedTask;
    }
}